import java.util.ArrayList;

public class Grammar {

	ArrayList<GrammarRule> ruleList;

	public Grammar() {

		ruleList = new ArrayList<GrammarRule>();
	}

	public void addGrammarRule(GrammarRule gr) {

		ruleList.add(gr);
	}

	public GrammarRule findGrammarRule(String s, RulePiece rp) {

		for (int i = 0; i < ruleList.size(); i++) {
			if (ruleList.get(i).getName().equals(s)) {
				if (withinFirstSet(i, rp.getType().substring(1))||withinFirstSet(i, rp.getContent())) {
					return ruleList.get(i);
				}
			}
		}
		return null;
	}

	public boolean withinFirstSet(int i, String firstString) {

		ArrayList<String> f = ruleList.get(i).getFirstSet();

		for (int k = 0; k < f.size(); k++) {
			if (f.get(k).equals(firstString)) {
				return true;
			}
		}

		return false;
	}
	
	public boolean findElipson(String s){
		for (int i = 0; i < ruleList.size(); i++) {
			if (ruleList.get(i).getName().equals(s)) {
				if (ruleList.get(i).getPiece(0).getType().equals("$EMPTY")) {
					return true;
				}
			}
		}
		return false;
	}

	public String toString() {
		String s = "";
		for (int i = 0; i < ruleList.size(); i++) {
			s += ruleList.get(i).toString() + "\n";
		}
		return s;

	}

	public GrammarRule getRule(int i) {
		return ruleList.get(i);

	}

	public int numRules() {

		return ruleList.size();

	}

	public void calculateRules() {
		for (int i = 0; i < numRules(); i++) {
			ruleList.get(i).calculateFirstSet();
		}
	}

}
